<script setup lang="ts">
import { getConsultOrderPre } from '@/api/consult'
import type { ConsultOrderPreData } from '@/types/consult'
import type { Patient } from '@/types/user'
import { consultStore } from '@/stores'
import { onMounted, ref } from 'vue'
import { getPatientDetial } from '@/api/user'
import { createConsultOrder, getConsultOrderPayUrl } from '@/api/consult'
import { showToast, showLoadingToast, showConfirmDialog, showDialog } from 'vant'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
// 获取订单信息
const store = consultStore()
const router = useRouter()
const payData = ref<ConsultOrderPreData>()
const payInfo = () => {
  getConsultOrderPre<ConsultOrderPreData>({
    type: store.consult.type,
    illnessType: store.consult.illnessType
  }).then(res => {
    payData.value = res.data
    // 设置默认优惠券
    store.setCoupon(payData.value.couponId)
  })
}
// 患者信息
const patien = ref<Patient>()
const patienDate = () => {
  if (!store.consult.patientId) return
  getPatientDetial<Patient>(store.consult.patientId).then(res => {
    patien.value = res.data
  })
}
const agree = ref(false)
onMounted(() => {
  if (!store.consult.type || !store.consult.illnessType || !store.consult.depId || !store.consult.patientId) {
    return showDialog({
      title: '温馨提示',
      message: '问诊信息不完整请重新填写，如有未支付的问诊订单可在问诊记录中继续支付',
      closeOnPopstate: false
    }).then(() => {
      router.push('/')
    })
  }
  payInfo()
  patienDate()
})

// 进行支付 （askgxl8276@sandbox.com）
// 1.控制支付抽屉弹出
// 2.关闭抽屉时确认框提示，仍要关闭跳转问诊记录，继续支付关闭提示
// 3.如果已经生成订单了，回退时拦截，
// 4.生成支付地址后跳转，
// 5.刷新页面时判断问诊记录是否存在，不存在就提示，确认后回到首页
const popupShow = ref(false)
const loding = ref(false)
const olderId = ref<string>()
const onPay = () => {
  if (!agree.value) return showToast('请勾选支付协议')
  loding.value = true
  createConsultOrder(store.consult).then(res => {
    loding.value = false
    olderId.value = res.data.id
    store.clear()
  })
  popupShow.value = !popupShow.value
}
const popupClose = () => {
  showConfirmDialog({
    title: '关闭支付',
    confirmButtonText: '继续支付',
    cancelButtonText: '仍要关闭',
    message: '取消支付将无法获取医生回复,医生接诊名额有限,是否确认关闭？'
  })
    .then(() => {
      popupShow.value = true
    })
    .catch(() => {
      olderId.value = ''
      router.push('/user/consult')
      popupShow.value = false
    })
}
// 路由拦截，离开组件时触发
onBeforeRouteLeave(() => {
  if (olderId.value) return false
})
// 支付方式
const paymentMethod = ref<0 | 1>()
// 订单支付
const pay = () => {
  if (!paymentMethod.value) return showToast('请选择支付方式')
  showLoadingToast({ message: '跳转支付中...', forbidClick: true, loadingType: 'spinner' })
  if (!olderId.value) return
  getConsultOrderPayUrl({
    paymentMethod: paymentMethod.value,
    orderId: olderId.value,
    payCallback: 'http://localhost:5173/room'
  }).then(res => {
    window.location.href = res.data.payUrl
  })
}
</script>
<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="问诊支付" />
    <div class="pay-info">
      <p class="tit">图文问诊 {{ payData?.payment }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${payData?.couponDeduction}`" />
      <van-cell title="积分抵扣" :value="`-¥${payData?.pointDeduction}`" />
      <van-cell title="实付款" :value="`¥${payData?.actualPayment}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patien?.name} | ${patien?.gender === 0 ? '男' : '女'}  | ${patien?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="store.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="agree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <van-submit-bar
      button-type="primary"
      :price="payData?.actualPayment ? payData?.actualPayment * 100 : 0"
      button-text="立即支付"
      text-align="left"
      :loading="loding"
      @click="onPay"
    />
    <van-popup
      closeable
      :close-on-click-overlay="false"
      v-model:show="popupShow"
      position="bottom"
      round
      :style="{ height: '40%' }"
      @close="popupClose"
    >
      <div class="pay-type">
        <p class="amount">￥{{ payData?.actualPayment.toFixed(2) }}</p>
        <van-cell-group>
          <van-cell title="微信支付" @click="paymentMethod = 0">
            <template #icon><cp-icons name="consult-wechat" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 0" /></template>
          </van-cell>
          <van-cell title="支付宝支付" @click="paymentMethod = 1">
            <template #icon><cp-icons name="consult-alipay" /></template>
            <template #extra><van-checkbox :checked="paymentMethod === 1" /></template>
          </van-cell>
        </van-cell-group>
        <div class="btn">
          <van-button type="primary" round block @click="pay">立即支付</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>
<style scoped lang="scss">
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
  .pay-type {
    .amount {
      padding: 20px;
      text-align: center;
      font-size: 16px;
      font-weight: bold;
    }
    .btn {
      padding: 15px;
    }
    .van-cell {
      align-items: center;
      .cp-icon {
        margin-right: 10px;
        font-size: 18px;
      }
      .van-checkbox :deep(.van-checkbox__icon) {
        font-size: 16px;
      }
    }
  }
}
</style>
